package com.lupan.tomcatStudy.jndi.common;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

/**
 * 说明：邮件发送工具
 *
 * @author lupan
 * @version 2016/6/23 17:30
 */
public class EmailUtil{

    private static Logger logger = LoggerFactory.getLogger(EmailUtil.class);

    public static void sendEmail(String[] addresses,String subject,String content) throws NamingException, MessagingException {

        //获取JNDI资源
        Context initCtx = new InitialContext();
        Context envCtx = (Context) initCtx.lookup("java:comp/env");
        Session session = (Session) envCtx.lookup("mail/Session");
        //开启Session的debug模式，这样就可以查看到程序发送Email的运行状态
        session.setDebug(true);

        Message message = new MimeMessage(session);

        logger.info("登录邮箱服务器用户："+session.getProperty("mail.smtp.user"));

        //构造邮件
        InternetAddress[] to = new InternetAddress[addresses.length];
        for(int i=0;i<addresses.length;i++) {
            to[i] = new InternetAddress(addresses[i]);
        }
        message.setFrom(new InternetAddress(session.getProperty("mail.smtp.user")));
        message.setRecipients(Message.RecipientType.TO, to);
        message.setSubject(subject);
        message.setContent(content,"text/plain;charset=UTF-8");
        Transport.send(message);
    }
}
